<?php

namespace Labirynt\CmsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DrawingController extends Controller
{
	public function getRepository()
	{
		return $this->getDoctrine()->getRepository('LabiryntCmsBundle:Drawing');
	}
	
	public function indexAction()
	{
		$current_drawing = $this->getRepository()->getLatestToDate();
		
		$params = array(
			'current_drawing' => $current_drawing,
			'previous' => $this->getRepository()->getPrevious($current_drawing),
			'next' => null
		);
		
		return $this->render('LabiryntCmsBundle:Drawing:index.html.twig', $params);
	}

	public function showAction($number)
	{
		$current_drawing = $this->getRepository()->findOneBy(array('number' => $number));

		if (!$current_drawing)
		{
			throw $this->createNotFoundException('Rysunek nie istnieje');
		}

		$params = array(
			'current_drawing' => $current_drawing,
			'next' => $this->getRepository()->getNext($current_drawing),
			'previous' => $this->getRepository()->getPrevious($current_drawing)
		);
		
		return $this->render('LabiryntCmsBundle:Drawing:index.html.twig', $params);
	}
	
	public function archiveAction()
	{
		$drawings = $this->getRepository()->getForArchive();
		$current_drawing = $this->getRepository()->getLatestToDate();
		
		$params = array(
			'drawings' => $drawings,
			'current_drawing' => $current_drawing
		);
		
		return $this->render('LabiryntCmsBundle:Drawing:archive.html.twig', $params);
	}
	
	public function languageAction($lang)
	{
		$this->getRequest()->getSession()->set('_locale', $lang);

		if (!in_array($lang, array('en', 'pl')))
		{
			throw $this->createNotFoundException('Niepoprawny język');
		}
		
		return $this->redirect($this->generateUrl('labirynt_cms_homepage'));
	}

    public function latestAction()
    {
        $current_drawing = $this->getRepository()->getLatestToDate();

		if (!$current_drawing)
		{
			throw $this->createNotFoundException('Brak rysunku do wyświetlenia.');
		}

        $extension = pathinfo($current_drawing->getAbsolutePath(), PATHINFO_EXTENSION);
        $basepath = basename($current_drawing->getAbsolutePath(), '.'.$extension);
        $filename = $current_drawing->getUploadRootDir().'/'.$basepath.'_s.'.$extension;

        $response = new Response();
        $response->headers->set('Content-type', mime_content_type($filename));
        $response->headers->set('Content-length', filesize($filename));
        $response->sendHeaders();
        $response->setContent(readfile($filename));

        return $response;
    }
}
